const app = getApp();

import services from '../../services/clockin';
import ddUtil from '../../utils/ddUtil';
import timeHelper from '../../utils/timeHelper';
import common from '../../utils/common';

Page({
  data: {
    userInfo: null, // 用户信息
    locAuthStatus: 0, // 0 未获取 1已授权 2未授权
    locationInfo: null, // 位置信息
    reason: '',
    fileList: [],
    isReady: false,
    clockType: '', // 打卡类型 0: 上班打卡 1: 下班打卡

    mapV2Enable: dd.canIUse('map.optimize'),
    longitude: '',
    latitude: '',
    controls: [
      {
        id: 1,
        iconPath: '/image/icon-map.png',
        position: {
          left: 10,
          bottom: 20,
          width: 28,
          height: 28
        },
        clickable: true
      }
    ],
    width: 0,
    height: 0,

    serverTime: 0, // 服务器时间
    currentTime: 0, // 当前时间
    showTime: '', // 显示时间
    pageTimer: null, // timer
    isLoading: false,
    showSuccessToast: false
  },
  onReady() {
    this.ctx = dd.createCanvasContext('canvas');
    this.mapCtx = dd.createMapContext('map');
  },
  async onLoad(query) {
    if (query && query.clockType) {
      this.setData({ clockType: Number(query.clockType) || 0 });
    }
    this.setData({
      userInfo: app.globalData.userInfo || {}
    });
    dd.showLoading({
      content: '加载中...',
      delay: 1000
    });
    await this.initData();
    this.setData({
      isReady: true
    });
    dd.hideLoading();
  },
  async onShow() {
    // if (this.data.isReady) {
    //   await this.initData();
    // }
  },
  onUnload() {
    this.clearPageTimer();
  },
  async initData() {
    await this.queryLocationInfo();
    if (this.data.userInfo && this.data.locationInfo) {
      this.moveToLocation();
      await this.queryAttendanceStatus();
      this.clearPageTimer();
      this.startPageTimer();
    }
  },
  // 获取位置信息
  async queryLocationInfo() {
    try {
      const res = await ddUtil.ddGetLocation();
      const { longitude, latitude, accuracy, province, city, address } = res || {};
      this.setData({
        locationInfo: {
          longitude: common.formatPosotion(longitude),
          latitude: common.formatPosotion(latitude),
          accuracy,
          province,
          city,
          address
        },
        longitude: common.formatPosotion(longitude),
        latitude: common.formatPosotion(latitude),
        locAuthStatus: 1
      });
      console.log('location:', this.data.locationInfo, this.data.locAuthStatus, res);
    } catch (error) {
      this.setData({ locAuthStatus: 2 });
      common.showErrorToast('无法获取位置信息，请打卡定位服务');
    }
  },
  moveToLocation() {
    if (dd.canIUse('createMapContext') && this.mapCtx) {
      this.mapCtx.moveToLocation();
    }
  },
  onControlTap() {
    this.initData();
  },
  initTimeInfo() {
    const serverTime = new Date().getTime();
    const currentTime = timeHelper.getSeconds(serverTime);
    app.globalData.serverTime = serverTime;
    const showTime = timeHelper.formatTime(currentTime);
    this.setData({ serverTime, currentTime, showTime });
  },
  // 获取打卡状态
  async queryAttendanceStatus() {
    try {
      this.initTimeInfo();
      const { unionid } = this.data.userInfo || {};
      const { longitude, latitude } = this.data.locationInfo || {};
      const params = { longitude, latitude };
      const res = await services.postNearStation(params, unionid);
      let constructionSite = {};
      if (res && res.data && res.data.length) {
        const currentStation = res.data.find((sitem) => sitem.allow_clock) || {};
        constructionSite = currentStation.station || {};
      }
      if (constructionSite && constructionSite.id) {
        // 回打卡页面
        dd.showToast({
          type: 'info',
          content: '您已到达工地',
          duration: 1500
        });
        dd.navigateBack();
      }
    } catch (error) {
      console.log('获取打卡状态失败', error);
      common.showErrorToast(error);
      this.setData({
        serverTime: 0, // 服务器时间
        currentTime: 0, // 当前时间
        showTime: '' // 显示时间
      });
    }
  },
  // 打卡
  async handleClockIn() {
    if (this.data.isLoading) {
      return;
    }
    this.setData({ isLoading: true });
    if (this.data.locAuthStatus === 2) {
      await this.initData(false);
      this.setData({ isLoading: false });
      return;
    }
    await this.queryPostAttendanceDo();
  },
  // 请求打卡
  async queryPostAttendanceDo() {
    try {
      const { reason, fileList, locationInfo, userInfo } = this.data;
      console.log('外勤打卡', reason);
      if (!locationInfo || !locationInfo.latitude || !locationInfo.longitude) {
        dd.showToast({
          type: 'info',
          content: '暂无定位信息',
          duration: 1500
        });
        this.setData({ isLoading: false });
        return;
      }
      if (!fileList || !fileList.length) {
        dd.showToast({
          type: 'info',
          content: '请上传图片',
          duration: 1500
        });
        this.setData({ isLoading: false });
        return;
      }
      if (!reason) {
        dd.showToast({
          type: 'info',
          content: '请填写备注',
          duration: 1500
        });
        this.setData({ isLoading: false });
        return;
      }
      let file = await common.handleGetImageBase64(this, fileList[0].path);
      if (!file) {
        return;
      }
      file = file.replace('data:image/jpeg;base64,', '');
      const params = {
        clock_type: this.data.clockType,
        unionid: userInfo.unionid || '',
        longitude: locationInfo.longitude,
        latitude: locationInfo.latitude,
        address: locationInfo.address,
        location: locationInfo.address,
        gps: `${locationInfo.longitude},${locationInfo.latitude}`,
        reason: reason || '',
        file: file
      };
      const res = await services.postClockPunchOuting(params);
      console.log('提交外勤打卡', params, res);
      if (res) {
        this.setData({ showSuccessToast: true });
        setTimeout(() => {
          dd.navigateBack();
          this.setData({ isLoading: false });
        }, 2000);
      } else {
        this.setData({ isLoading: false });
        common.showErrorToast(res);
      }
    } catch (error) {
      this.setData({ isLoading: false });
      console.log('打卡失败', error);
      common.showErrorToast(error);
    }
  },
  handleCloseToast() {
    this.setData({
      showSuccessToast: false
    });
  },
  handleChangeReason(value, e) {
    this.setData({ reason: value });
  },
  // 开始计时
  startPageTimer() {
    const pageTimer = setInterval(() => {
      const currentTime = this.data.currentTime + 1;
      const showTime = timeHelper.formatTime(currentTime);
      this.setData({ currentTime, showTime });
    }, 1000);
    this.setData({ pageTimer });
  },
  // 清除计时
  clearPageTimer() {
    if (this.data.pageTimer) {
      clearInterval(this.data.pageTimer);
      this.setData({ pageTimer: null });
    }
  },
  onChange(fileList) {
    this.setData({ fileList });
  },
  onUpload(localFile) {
    if (!localFile || !localFile.path) {
      return;
    }
    return new Promise((resolve) => {
      resolve(localFile.path);
    });
  }
});
